
import UIKit

let kUserManager = UserManager.instance

class UserManager: NSObject {
    
    /// 构造
    static let instance = UserManager()
    /// token
    fileprivate(set) var accessToken = ""
    var loginResp = LoginResp() {
        didSet {
            accessToken = loginResp.token
            
            // 存储
            UserDefaults.standard.synchronize()
            UserDefaults.standard.setValue(loginResp.toJSONString(), forKey: UserManager.userLoginRespLocalStorageKay)
        }
    }
    
    /// 当前用户信息
    private(set) var userModel = UserModel()
    
    private(set) var isRefreshToken = false
    
    /// 是否登录
    var isLogin: Bool {
        accessToken.count > 0
    }
    
    /// 是否是会员
    var isVip: Bool {
        userModel.memberType > 0
    }
    
    // keys
    static let userLocalStorageKay = "LocalStorageUserInfomationKay"
    static let userLoginRespLocalStorageKay = "LocalStorageLoginResponseKay"
    
    override init() {
        super.init()
        
        // 加载用户信息
        loadLocalUserInfomation()
    }
    
    /// 加载本地存储的用户信息
    func loadLocalUserInfomation() {
                
        // 读取本地Token
        UserDefaults.standard.synchronize()
        if let loginRespJson = UserDefaults.standard.value(forKey: UserManager.userLoginRespLocalStorageKay) as? String, let resp = Mapper<LoginResp>().map(JSONString: loginRespJson) {
            loginSaveToken(resp: resp, isRequestUserInfo: false)
        }
        
        guard isLogin else { return }
        DispatchQueue.global().async {
            // 请求服务器用户信息
            self.getUserInfomation { _ in }
        }
    }

    /// 登录存储Token
    func loginSaveToken(resp: LoginResp, isRequestUserInfo: Bool = true) {
        
        // 更新token
        loginResp = resp
        
        if isRequestUserInfo {
            kUserManager.getUserInfomation { dialog in
                DispatchQueue.main.async {
                    NotificationCenter.default.post(name: NSNotification.Name("LoginSuccessNotification"), object: nil)
                }
            }
        }
        
//        // 记录过期时间
//        OAuthAuthenticator.expirationDuration = TimeInterval(resp.expiresTime/1000)
//        MYLog("过期时间: \(Date(timeIntervalSince1970: TimeInterval(resp.expiresTime/1000 + 8*60*60))),\(OAuthAuthenticator.expirationDuration/1000 + 8*60*60)s过期")
//        
//        // 初始化过滤器
//        DispatchQueue.global().async {
//            apiProvider = AppProvider.createAuthProvider()
//        }
        
    }
    
    /// 退出登录
    func logout(completeHandle: @escaping NetworkRequestHandle) {
        
        guard self.accessToken.count > 0 else { return }

        apiProvider.request(api: .logout) { [weak self] json, jsonArr, code in

            MYLog("退出登录: ",json)

            var dialog = DialogMessage()
            dialog.code = code

            guard code == 200, let pm = Mapper<ResponseModel>().map(JSON: json) else { return completeHandle(dialog) }

            dialog.code = pm.code
            dialog.message = pm.msg

            guard pm.code == 200, let strongSelf = self else { return completeHandle(dialog) }
            strongSelf.logoutClearData()
            DispatchQueue.main.async {
                AppAudioManager.shared.resetInitState()
            }
            completeHandle(dialog)

        } failureHandler: { error in
            completeHandle(DialogMessage())
        }

    }
    /// 退出登录清除数据
    func logoutClearData() {
        
        // 清除登录信息
        let userDefaults = UserDefaults.standard
        userDefaults.removeObject(forKey: UserManager.userLocalStorageKay)
        userDefaults.removeObject(forKey: UserManager.userLoginRespLocalStorageKay)
        userDefaults.synchronize()
        
        // 清除临时
        self.accessToken = ""
        self.userModel = UserModel()

    }
    /// 登录失效
    func loginLoseEfficacy() {
        logoutClearData()
    }
    /// 去登录
    func toLogin() {
        guard let currentVC = Utils.getTopVC() else { return }
        currentVC.showDetailViewController(BaseNavigationController(rootViewController: LoginVC(viewType: .account)), sender: nil)
    }
}

// MARK: - 更新数据
extension UserManager {
    
    /// 获取远程数据信息
    func getUserInfomation(completeHandle: @escaping NetworkRequestHandle) {
    
        guard isLogin else { return }
        apiProvider.request(api: .getUserInfo) { [weak self] json, jsonArr, code in
            
            MYLog("获取用户信息：",json)
            
            var dialog = DialogMessage()
            guard let strongSelf = self,let pm = Mapper<ResponseModel>().map(JSON: json), code == 200 else { return completeHandle(dialog) }
            dialog.code = pm.code
            dialog.message = pm.msg
            guard pm.code == 200, let data = pm.data as? [String: Any], let model = Mapper<UserModel>().map(JSON: data) else {
                completeHandle(dialog)
                return
            }
            
            // 保存用户信息
            strongSelf.userModel = model
            dialog.data = model
            
            dialog.message = "获取成功"
            dialog.isSuccess = true
            completeHandle(dialog)
            
        } failureHandler: { error in
            completeHandle(DialogMessage())
        }
        
    }
    
    // MARK: - 获取App是否升级
    static func checkUpgrade() {
        
        apiProvider.request(api: .upgrade(params: ["platform": 2])) { json, jsonArr, code in
            
            MYLog("获取升级信息", json, jsonArr, code)
            
            var dialog = DialogMessage()
            guard let pm = Mapper<ResponseModel>().map(JSON: json), code == 200 else { return }
            dialog.code = pm.code
            dialog.message = pm.msg
            guard pm.code == 200, let data = pm.data as? [String: Any], let model = Mapper<UpgradeModel>().map(JSON: data) else { return }
            
            if model.versionCode > "\(Constant.versionCode)" && model.forceUpgrade == true {
                DispatchQueue.main.async {
                    UpgradeAlertView().show(upgradeModel: model)
                }
            }
            
            dialog.data = model
            
        } failureHandler: { _ in }
        
    }
    
}

// MARK: - 更新app数据
class UpgradeModel: Mappable {

    var createTime = ""
    var forceUpgrade = true
    var id = 2
    var installAddressAndroid = ""
    var installAddressIos = ""
    var name = ""
    var packageSize = 0
    var platform = 2
    var remarks = ""
    var status = 0
    var updateTime = ""
    var upgradeInstructions = ""
    var upgradeInstructionsEnglish = ""
    var versionCode = "2"
    var versionName = ""
    
    init() {
        
    }
    
    required init?(map: ObjectMapper.Map) {
        
    }
    
    func mapping(map: ObjectMapper.Map) {
        
        createTime <- map["createTime"]
        forceUpgrade <- map["forceUpgrade"]
        id <- map["id"]
        installAddressAndroid <- map["installAddressAndroid"]
        installAddressIos <- map["installAddressIos"]
        name <- map["name"]
        packageSize <- map["packageSize"]
        platform <- map["platform"]
        remarks <- map["remarks"]
        status <- map["status"]
        updateTime <- map["updateTime"]
        upgradeInstructions <- map["upgradeInstructions"]
        upgradeInstructionsEnglish <- map["upgradeInstructionsEnglish"]
        versionCode <- map["versionCode"]
        versionName <- map["versionName"]
        
    }
    
}


